package com.example.demo.controller;

import com.example.demo.constant.Constants;
import com.example.demo.model.Blog;
import com.example.demo.model.User;
import com.example.demo.service.BlogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpMediaTypeException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.scanner.Constant;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogController {
    //获得博客列表
    @Autowired
    private BlogService blogService;
    @RequestMapping("/getlist")
    public List<Blog> getBlogList(){
        return blogService.getBlogList();
    }
    @RequestMapping("/getBlogDetail")
    public Blog getBlogDetail(Integer blogId,HttpServletRequest request){
        Blog blog = blogService.getBlogDetail(blogId);
        //判断作者是否是登录用户
        User user = (User)request.getSession(false).getAttribute(Constants.SESSION_USER_INFO);
        if(blog != null && user != null && blog.getUserId() == user.getId()){
            blog.setLoginUser(1);
        }
        return blog;
    }
    //发布博客
    @RequestMapping("/add")
    public boolean addBlog(Blog blog, HttpServletRequest request){
        User user = (User)request.getSession(false).getAttribute(Constants.SESSION_USER_INFO);
        if(user == null || user.getId() < 0){
            return false;
        }
        //设置作者
        blog.setUserId(user.getId());
        Integer num = blogService.insert(blog);
        if(num == 1){
            return true;
        }
        return false;
    }
    @RequestMapping("/update")
    public boolean update(Blog blog){
        Integer num = blogService.update(blog);
        if(num == 1){
            return true;
        }
        return false;
    }
    @RequestMapping("/delete")
    public boolean delete(Integer blogId){
        log.info("delete blogId" + blogId);
        Integer num = blogService.delete(blogId);
        return num==1?true:false;
    }
}
